package cn.wolfcode.${project}.service.impl;

import cn.wolfcode.${project}.domain.${capitalize};
import cn.wolfcode.${project}.query.${capitalize}QueryObject;
import cn.wolfcode.${project}.repository.${capitalize}Repository;
import cn.wolfcode.${project}.service.${capitalize}Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author ${author}
 * @Date ${.now?string("yyyy-MM-dd HH:mm")}
 */
@Service
public class ${capitalize}ServiceImpl implements ${capitalize}Service {
    @Autowired
    private ${capitalize}Repository ${uncapitalize}Repository;

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public void save(${capitalize} ${uncapitalize}) {
        ${uncapitalize}.setId(null);
        ${uncapitalize}Repository.insert(${uncapitalize});
    }

    @Override
    public void update(${capitalize} ${uncapitalize}) {
        ${uncapitalize}Repository.save(${uncapitalize});
    }

    @Override
    public void delete(String id) {
        ${uncapitalize}Repository.deleteById(id);
    }

    @Override
    public ${capitalize} get(String id) {
        return ${uncapitalize}Repository.findById(id).orElse(null);
    }

    @Override
    public List<${capitalize}> list() {
        return ${uncapitalize}Repository.findAll();
    }

    /**
    * ${chinese}高级查询
    * @param qo 查询条件
    * @return
    */
    @Override
    public Page<${capitalize}> query(${capitalize}QueryObject qo) {

        Query query = new Query();

        long count = mongoTemplate.count(query, ${capitalize}.class);
        if (count == 0) {
            return Page.empty();
        }

        Pageable pageRequest = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(), Sort.Direction.ASC,"sequence");
        query.with(pageRequest);
        List<${capitalize}> list = mongoTemplate.find(query, ${capitalize}.class);
        return new PageImpl<${capitalize}>(list,pageRequest,count);
    }

    /**
     * 新增或编辑${chinese}
     * @param ${uncapitalize}
     */
    @Override
    public void saveOrUpdate(${capitalize} ${uncapitalize}) {
        if (StringUtils.hasLength(${uncapitalize}.getId())) {
            //编辑
            this.update(${uncapitalize});
        }else {
            //新增
            this.save(${uncapitalize});
        }
    }
}
